package com.sxkf.template.controller;


import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sxkf.core.api.vo.R;
import com.sxkf.core.third.im.entity.Message;
import com.sxkf.core.third.im.entity.Score;
import com.sxkf.core.third.im.entity.ScoreDto;
import com.sxkf.core.third.im.entity.SendMessage;
import com.sxkf.core.third.im.service.YxService;
import com.sxkf.system.entity.SysUser;
import com.sxkf.system.service.ISysUserService;
import com.sxkf.template.entity.AfterSaleEvaluation;
import com.sxkf.template.entity.Product;
import com.sxkf.template.entity.Store;
import com.sxkf.template.mapper.AfterSaleEvaluationMapper;
import com.sxkf.template.service.AfterSaleEvaluationService;
import com.sxkf.template.service.MessageService;
import com.sxkf.template.service.ProductService;
import com.sxkf.template.service.StoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;


@Api(tags = "发送消息")
@RestController
@RequestMapping("/msg")
public class MessageController {

    @Resource
    private MessageService messageService;

    @Resource
    private ProductService productService;

    @Resource
    private YxService yxService;

    @Resource
    private StoreService storeService;

    @Resource
    private ISysUserService sysUserService;

    @Resource
    private AfterSaleEvaluationMapper afterSaleEvaluationMapper;




    @ApiOperation("发送商品消息")
    @GetMapping("/product")
    public R<String> product(@RequestParam @ApiParam("发送者 用户id") String senderId,
                             @RequestParam @ApiParam("接收者 用户id") String receiverId,
                             @RequestParam @ApiParam("发送的商品id") String productId) {

        // 现在receiverId是店铺id，店铺id就是商家用户的im用户ID

        Product product = productService.getById(productId);
        Product product1 = new Product();
        product1.setId(product.getId());
        product1.setName(product.getName());
        product1.setImageUrl(product.getImageUrl());
        product1.setLowestPrice(product.getLowestPrice());

        Message message = new Message();
        message.setMessage_type(100);
        message.setSub_type(10);
        message.setText("商品信息");
        message.setAttachment(product1);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setMessage(message);
//        sendMessage.setExtension(JSON.toJSONString(product));
        Boolean isSend = yxService.sendMessage(senderId, receiverId, sendMessage);
        if (isSend){
            return R.success("发送成功");
        }else {
            return R.error("发送失败");
        }

    }


    @ApiOperation("发送评价")
    @PostMapping("/score")
    public R<String> score(@RequestBody @ApiParam("评价信息") Score score) {

        Message message = new Message();
        message.setMessage_type(100);
        message.setSub_type(11);
        message.setText("服务评价信息");
        message.setAttachment(score.getScore());
        SendMessage sendMessage = new SendMessage();
        sendMessage.setMessage(message);
//        sendMessage.setExtension(JSON.toJSONString(scoreDto));

        // 根据接收者用户id查店铺id
        SysUser sysUser = sysUserService.getById(score.getReceiverId());

        AfterSaleEvaluation evaluation = new AfterSaleEvaluation();
        BeanUtils.copyProperties(score, evaluation);
        BeanUtils.copyProperties(score.getScore(), evaluation);
        evaluation.setStoreId(sysUser.getStoreId());
        afterSaleEvaluationMapper.insert(evaluation);

        long count = afterSaleEvaluationMapper.selectCount(new LambdaQueryWrapper<AfterSaleEvaluation>()
                .eq(AfterSaleEvaluation::getStoreId, evaluation.getStoreId())
        );

        List<Object> results = afterSaleEvaluationMapper.selectObjs(new QueryWrapper<AfterSaleEvaluation>()
                .select("SUM(star) as total")
        );

        // 获取总和，处理可能为空的情况
        BigDecimal total = results.isEmpty() ? BigDecimal.ZERO : ((BigDecimal) results.get(0)).divide(BigDecimal.valueOf(count), RoundingMode.FLOOR);
        // 获取总和评价
        double avg = storeService.getAvgEvaluation(sysUser.getStoreId(),total,count,BigDecimal.ZERO,0L);
        Store store = new Store();
        store.setId(sysUser.getStoreId());
        store.setSoldEvalution(total.doubleValue());
        store.setAvgEvalution(avg);
        storeService.updateById(store);


        Boolean isSend = yxService.sendMessage(score.getSenderId(), score.getReceiverId(), sendMessage);
        if (isSend){
            return R.success("发送成功");
        }else {
            return R.error("发送失败");
        }

    }

    @ApiOperation("咨询内容")
    @GetMapping("/productPage")
    public R<IPage<Product>> productPage(@RequestParam Integer pageNo,
                                         @RequestParam Integer pageSize,
                                         @RequestParam
                                         @ApiParam("用户id") String userId,
                                         @RequestParam
                                         @ApiParam("搜索类型： 1=店铺商品 2=浏览记录 3=已购买 4=购物车 5=我的收藏") String searchType,
                                         @RequestParam
                                         @ApiParam("店铺id") String storeId) {

        IPage<Product> page = messageService.productPage(pageNo,pageSize,userId,searchType,storeId);

        return R.success(page);

    }


}
